﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Go;

namespace fhs
{
    public partial class DataViewForm : Form
    {
        static public DataViewForm obj;
        static private work_engine dataSave;

        public DataViewForm()
        {
            obj = this;
            dataSave = new work_engine();
            dataSave.run(background: true);
            InitializeComponent();
        }

        private void DataShowForm_Load(object sender, EventArgs e)
        {

        }

        static public void Append(double X, double Y, double U, double errorBlLen, double errorCellLen)
        {
            DateTime now = DateTime.Now;
            if (dataSave.service.count < 100)
            {
                dataSave.service.post(delegate ()
                {
                    try
                    {
                        string file = $"./test_data/{now.ToString("yyyy-MM-dd")}.csv";
                        if (!File.Exists(file))
                        {
                            Directory.CreateDirectory("./test_data");
                            File.AppendAllText(file, "时间,补偿X,补偿Y,补偿U,Bl偏差,Cell偏差\r\n");
                        }
                        string newLine = $"{now.ToString("HH.mm.ss")},{X.ToString("0.00")},{Y.ToString("0.00")},{U.ToString("0.00")},{errorCellLen.ToString("0.00")},{errorBlLen.ToString("0.00")}\r\n";
                        File.AppendAllText(file, newLine);
                    }
                    catch (Exception) { }
                });
            }
            if (obj.dataGridView1.RowCount > 99)
            {
                obj.dataGridView1.Rows.RemoveAt(99);
            }
            DataGridViewRow newRows = new DataGridViewRow();
            newRows.CreateCells(obj.dataGridView1);
            newRows.Cells[obj.dataGridView1.Columns["时间"].Index].Value = now.ToString("HH.mm.ss");
            newRows.Cells[obj.dataGridView1.Columns["补偿X"].Index].Value = $"{X.ToString("0.00")}mm";
            newRows.Cells[obj.dataGridView1.Columns["补偿Y"].Index].Value = $"{Y.ToString("0.00")}mm";
            newRows.Cells[obj.dataGridView1.Columns["补偿U"].Index].Value = $"{U.ToString("0.00")}°";
            newRows.Cells[obj.dataGridView1.Columns["BL偏差"].Index].Value = $"{errorBlLen.ToString("0.00")}mm";
            newRows.Cells[obj.dataGridView1.Columns["Cell偏差"].Index].Value = $"{errorCellLen.ToString("0.00")}mm";
            obj.dataGridView1.Rows.Insert(0, newRows);
        }
    }
}
